#! /usr/bin/env python
# -*- coding: utf-8 -*-
import json, os
from wechat_alert.settings import USER_INFO_FILE
from wechat_alert.sender.send2tag import WeChat2tag
from wechat_alert.sender.send2group import WeChat2group


#告警信息组读取
def get_saved_users():
    with open(USER_INFO_FILE, 'rb') as f:
        return json.loads(f.read())

#告警分发
def parse_user_info(data):
    #默认运维组
    #party_id = '7'
    party_id = ''
    party_member = ''
    party_name = ''
    party_sms = ''
    party_email = ''
    saved_groups = get_saved_users()
    if type(data['group']).__name__ != 'list':
       data['group'] = data['group'].split('|')
    for tag in  data['group']:
        if tag in saved_groups.keys():
           party_id += "|"+saved_groups[tag]['module_chat_id']
           party_member += saved_groups[tag]['module_members']
           party_name += saved_groups[tag]['module_name']
           party_sms += saved_groups[tag]['module_sms']
           party_email +=saved_groups[tag]['module_email']
#         #else:
#         #   party_id += '14'
#         #   party_member += '王银龙、罗浩'+"|"
#         #   party_name += "告警兜底"+"|"
#         #   print party_id,party_member,party_name
    return {'id': party_id, 'name': party_name, 'member': party_member, 'sms': party_sms, 'email': party_email}


def send2group(title,msg):
    wechat2group = WeChat2group(title, msg)
    wechat2group.access_token()
    wechat2group.sendMessage()

def send2tag(title,msg,party_id):
    wechat2tag = WeChat2tag(title, msg, party_id)
    wechat2tag.access_token()
    wechat2tag.sendMessage()

#Prometheus告警处理流程
def prometheus_alert(data):
    if 'group' in data and not data['group'] is '':
        party_info = parse_user_info(data)
        # print("data=====>",data)
        message = data['description']+"\n"+"告警模块："+ party_info['name']+"\n"+"负责人："+party_info['member']+"\n"+"告警时间："+data['timestamp']
        # print("message=====>", message)
        # print("message=====type>", type(message))
        party_id = party_info['id']
        if data['level'] == "high":
           print("high-触发: tag")
           send2tag(data['summary'], message, party_id)
           # send2group(data['summary'], message)
        elif data['level']== "disaster":
           print ("disaster-触发: tag/group")
           send2tag(data['summary'], message, party_id)
           send2group(data['summary'], message)
        else:
            print("条件不足，不告警")
    else:
        pass
